package com.cat.chapter039;

import java.util.ArrayList;
/**
 * @author cat
 * @description https://leetcode.cn/problems/basic-calculator-ii/
 * @create 2025/7/9 16:53
 * @since JDK17
 */

public class Solution01 {
    ArrayList<Integer> nums = new ArrayList<>();
    ArrayList<Character> symbol = new ArrayList<>();

    void push(int num, char opt) {
        Character topOpt = symbol.size() != 0 ? symbol.get(symbol.size() - 1) : '+';   // 上一个操作符
        if (topOpt == '*' || topOpt == '/') {   // 乘或除
            Integer topNum = nums.remove(nums.size() - 1);
            symbol.remove(symbol.size() - 1);
            nums.add((topOpt == '*' ? topNum * num : topNum / num));
        } else {
            nums.add(num);
        }
        symbol.add(opt);
    }

    public int calculate(String s) {
        char[] chars = s.toCharArray();
        int cur = 0;
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == ' ') { // 空格不管
                continue;
            }
            if (c >= '0' && c <= '9') { // 数字
                cur = cur * 10 + c - '0';   // 字符转换为数字
            } else {
                push(cur, c);
                cur = 0;
            }
        }
        push(cur, '+');
        return compute();
    }



    public int compute() {
        int ans = nums.get(0);
        for (int i = 1; i < nums.size(); i++) {
            ans += symbol.get(i - 1) == '+' ? nums.get(i) : -nums.get(i);
        }
        return ans;
    }
}
